package org.heart.controller.userInfoController;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.heart.common.CommonResult;
import org.heart.entity.dto.FriendRelationship;
import org.heart.entity.dto.UserBaseInfo;
import org.heart.service.IFriendRelationshipService;
import org.heart.service.IUserBaseInfoService;
import org.heart.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.heart.utils.CommonUtils.daysBetweenNow;

@RequestMapping("/wx")
@RestController
@Slf4j
public class WxLoginController {

    @Resource
    private IFriendRelationshipService iFriendRelationshipService;

    @Resource
    private IUserBaseInfoService ilUserBaseInfoService;

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appAppSecret}")
    private String appAppSecret;
    @Value("${wx.host}")
    private String host;
    @Value("${wx.api}")
    private String api;

    @GetMapping("/wxLogin")
    public CommonResult WxLoginHandle(@RequestParam(value = "code",required = true) String code,
                                      @RequestParam(value = "userName",required = false,defaultValue = "微信用户") String userName,
                                      @RequestParam(value = "avatarUl",required = false,defaultValue = "https://www.xiguama.com/content/templates/default/static/images/randem/pic2.jpg") String avatarUl){

        log.info("微信一键登录处理，请求code为：{}",code);

        if(StringUtils.isEmpty(code)){
            log.info("微信登录接口请求失败，code 为空");
            return CommonResult.errorResponse("接口请求失败，code 不能为空！");
        }

        Map<String,String> querys = new HashMap<String, String>();

        querys.put("appid",appId);
        querys.put("secret",appAppSecret);
        querys.put("js_code",code);
        querys.put("grant_type","authorization_code");

        Map<String,String> header = new HashMap<String, String>();

        try {
            HttpResponse response =  HttpUtils.doGet(host,api,header,querys);

            Map<String, Object> resultMap = JSONUtil.parseObj(EntityUtils.toString(response.getEntity()));

            String sessionKey = (String) resultMap.get("session_key");
            String openId = (String) resultMap.get("openid");
            String errcode = (String) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");

            if(StringUtils.isEmpty(openId)){
                log.info("openId 获取失败，错误信息码：{}，错误信息为：{}",errcode,errmsg);
                return CommonResult.errorResponse("远程请求失败！请重试！");
            }else{
                log.info("openId :{},sessionKey ：{}",openId,sessionKey);
            }

            UserBaseInfo userInfo = new UserBaseInfo();
            userInfo.setAvatarUrl(avatarUl);
            userInfo.setNickname(userName);
            userInfo.setNickname(userName);
            userInfo.setOpenid(openId);
            userInfo.setUnionid(sessionKey);
            UserBaseInfo userInfos =  ilUserBaseInfoService.loginOrRegister(userInfo);
            System.out.println(userInfos.getRegisterTime());
            System.out.println(daysBetweenNow(userInfos.getRegisterTime()));
            userInfos.setUserDay(daysBetweenNow(userInfos.getRegisterTime())); //用户登录时长
            QueryWrapper<FriendRelationship> qw = new QueryWrapper<>();
            qw.eq("user_id",userInfos.getUserId());
            List<FriendRelationship> list = iFriendRelationshipService.list(qw);
            if(ObjectUtil.isEmpty(list)){
                userInfos.setUserCnt(0);
            }else{
                userInfos.setUserCnt(list.size());
            }

            if(ObjectUtil.isNull(userInfos)){
                return CommonResult.errorResponse("登录失败！");
            }else{
                return CommonResult.successResponse(userInfos,"登录成功");
            }

        } catch (Exception e){
            log.info("远程请求失败！错误信息为：{}",e.getMessage());
            System.out.println(e);
            return CommonResult.errorResponse("远程请求失败！请重试！");
        }

    }
}
